package LeetCode.leetcode707;

class MyLinkedList {

    //虚拟头结点
    private Node virtualNode;

    public MyLinkedList() {
        virtualNode = new Node();
    }

    public int get(int index) {
        if (index < 0)
            return -1;
        Node p = virtualNode;
        for (int i = 0; i <= index; i++) {
            if (p.next != null) {
                p = p.next;
            } else {
                return -1;
            }
        }
        return p.val;
    }

    public void addAtHead(int val) {
        Node node1 = new Node();
        node1.val = val;
        node1.next = virtualNode.next;
        virtualNode.next = node1;
    }

    public void addAtTail(int val) {
        Node p = virtualNode;
        while (p.next != null) {
            p = p.next;
        }
        Node tail = new Node();
        tail.val = val;
        p.next = tail;

    }

    public void addAtIndex(int index, int val) {
        if (index <= 0) {
            Node node1 = new Node();
            node1.val = val;
            node1.next = virtualNode.next;
            virtualNode.next = node1;
        } else {
            Node p = virtualNode;
            for (int i = 0; i < index; i++) {
                if (p.next != null) {
                    p = p.next;
                } else {
                    return;
                }
            }
            Node t = new Node();
            t.val = val;
            t.next = p.next;
            p.next = t;
        }
    }

    public void deleteAtIndex(int index) {
        if (index < 0)
            return;
        Node p = virtualNode;
        for (int i = 0; i < index; i++) {
            if (p.next != null) {
                p = p.next;
            } else {
                return;
            }
        }
        if (p.next != null) {
            p.next = p.next.next;
        }
    }



    public static class Node {
        int val;
        Node next;
    }
}
